import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:kong/domain/exception/auth_exception.dart';
import 'package:kong/domain/repository/api_repository.dart';
import 'package:kong/domain/repository/local_storage_repository.dart';
import 'package:kong/domain/model/request/login.dart';
import 'package:kong/domain/model/response/login.dart';

class LoginController extends GetxController {
  final LocalRepositoryInterface local;
  final ApiRepositoryInterface api;

  LoginController({
    this.local,
    this.api,
  });

  final usernameTextController = TextEditingController();
  final passwordTextController = TextEditingController();

  final count = 0.obs;
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
  void increment() => count.value++;

  Future<bool> login() async {
    final username = usernameTextController.text;
    final password = passwordTextController.text;
    try {
      final LoginResponse response = await api.login(
        LoginRequest(username, password),
      );
      local.setToken(response.token);
      local.setUser(response.user);
      return true;
    } on AuthException catch (_) {
      return false;
    }
  }
}
